package storm;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.log4j.Logger;

/**
 * @author 李岩飞
 * @email eliyanfei@126.com
 * @date 2018年5月10日下午2:07:54
 */
public class StormKafakProductor implements Runnable {
	static Logger logger = Logger.getLogger(StormKafakProductor.class);

	public StormKafakProductor() {
	}

	KafkaProducer<String, String> producer = null;

	private void initProductor() {
		String BROKER_LIST = "localhost:9092";
		Properties props = new Properties();
		props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, BROKER_LIST);
		props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
		props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
				"org.apache.kafka.common.serialization.StringSerializer");
		props.put("metadata.broker.list", BROKER_LIST);

		logger.warn("Flow 生产者已启动...");
		producer = new KafkaProducer<String, String>(props);
	}

	@Override
	protected Object clone() throws CloneNotSupportedException {
		try {
			producer.close();
		} catch (Exception e) {
		}
		return super.clone();
	}

	@Override
	public void run() {
		initProductor();
		while (true) {
			try {
				new File("E:\\apache-tomcat-7.0.34\\logs").listFiles(new FileFilter() {
					public boolean accept(File f) {
						if (f.isFile() && f.getName().startsWith("localhost_access_log")) {
							BufferedReader br = null;
							String line;
							try {
								br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
								while ((line = br.readLine()) != null) {
									String[] values = line.split(" ");
									LogBean logBean = new LogBean();
									logBean.ip = values[0];
									logBean.values = values;
									producer.send(new ProducerRecord<String, String>("log2",
											System.currentTimeMillis() + "-key", line));
								}
							} catch (Exception e) {
							} finally {
								try {
									br.close();
								} catch (IOException e) {
									e.printStackTrace();
								}
							}
						}
						return false;
					}
				});

				TimeUnit.SECONDS.sleep(3);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void startup() {
		new Thread(this).start();
	}

	public static void main(String[] args) {
		new StormKafakProductor().startup();
	}
}
